import React, { useEffect, useState, useRef } from 'react'
import { Table, Button, Select, Form, Input, Row, Col, DatePicker, Radio, Space, Drawer, message, Modal, Popconfirm, Breadcrumb } from 'antd';
import moment from 'moment'
import {Navigate} from 'react-router-dom'
import { downloadUserInfoApi } from '../../apis/requestFile'
import userApi from '../../apis/user';
import Setting from '../../assets/images/设置.png'
import Looking from '../../assets/images/查看.png'
import Zhanghu from '../../assets/images/账户.png'
import Juese from '../../assets/images/角色.png'
import Xingbie from '../../assets/images/性别.png'
import Dianhua from '../../assets/images/电话.png'
import Youxiang from '../../assets/images/邮箱.png'
import Bumen from '../../assets/images/部门.png'
import Zhuangtai from '../../assets/images/状态.png'
import Chuangjian from '../../assets/images/创建时间.png'
import Denglu from '../../assets/images/最近登录.png'
import Miaoshu from '../../assets/images/描述.png'
export default function user() {
    const [listUser, setListUser] = useState([])
    const [userInf, setUserInf] = useState({})
    const [totalUser, setTotalUser] = useState(0)
    const formRef = useRef()
    const pageSize = '50'
    //新增用户功能
    const [open, setOpen] = useState(false);
    const showDefaultDrawer = () => {
        setOpen(true);
    };
    const onClose = () => {
        setOpen(false);
    };

    //修改用户功能
    const [openEdit, setOpenEdit] = useState(false)
    const [editUser, setEditUser] = useState({})
    const onCloseEdit = () => {
        setOpenEdit(false);
    };
    const [formEdit] = Form.useForm()
    const showDrawer = (e) => {
        setEditUser(e)
        formEdit.setFieldsValue({
            username: e.username,
            email: e.email,
            mobile: e.mobile,
            roleId: e.roleId,
            deptId: e.deptId,
            status: e.status,
            ssex: e.ssex
        })
        setOpenEdit(true);
    };
    //用户信息model框功能
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = (e) => {
        setIsModalOpen(true);
        setUserInf(e)
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    //表格筛选功能
    const [filteredInfo, setFilteredInfo] = useState({});
    const [sortedInfo, setSortedInfo] = useState({});
    const handleChangeSort = (pagination, filters, sorter) => {
        if (filters) {
            if (filters.ssex) {
                userApi.getAllUser({ pageSize: pageSize, ssex: filters.ssex[0] }).then(res => {
                    setListUser([...res.data.rows])
                    setTotalUser(res.data.total)
                })
            } else if (filters.status) {
                userApi.getAllUser({ pageSize: pageSize, status: filters.status[0] }).then(res => {
                    setListUser([...res.data.rows])
                    setTotalUser(res.data.total)
                })
            }
        }
        setFilteredInfo(filters);
        setSortedInfo(sorter);
    };
    //表格标题栏
    const columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            sorter: (a, b) => a.username.length - b.username.length,
            sortOrder: sortedInfo.columnKey === 'username' ? sortedInfo.order : null,
        },
        {
            title: '性别',
            dataIndex: 'ssex',
            key: 'ssex',
            filters: [
                {
                    text: '男',
                    value: '0',
                },
                {
                    text: '保密',
                    value: '2'
                }
            ],
            filteredValue: filteredInfo.ssex || null,
            onFilter: (value, record) => record.ssex == value,
            render: (record) => {
                return getSex(record)
            }
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
        },
        {
            title: '部门',
            dataIndex: 'deptName',
            key: 'deptName',
        },
        {
            title: '电话',
            dataIndex: 'mobile',
            key: 'mobile',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (record) => {
                return getStatus(record)
            },
            filters: [
                { text: '有效', value: '1' },
                { text: '锁定', value: '0' }
            ],
            filteredValue: filteredInfo.status || null,
            onFilter: (value, record) => record.status == value
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',

            sorter: (a, b) => Date.parse(a.createTime) - Date.parse(b.createTime),
            sortOrder: sortedInfo.columnKey === 'createTime' ? sortedInfo.order : null,
        },
        {
            title: '操作',
            dataIndex: '',
            key: 'x',
            render: (record) =>
                <div>
                    <img src={Setting} style={{ width: 15, height: 15, cursor: 'pointer' }} onClick={() => showDrawer(record)} />
                    <img src={Looking} style={{ width: 20, height: 20, marginLeft: 10, cursor: 'pointer' }} onClick={() => showModal(record)} />
                </div>
        },
    ];

    //删除功能
    const [delUserInfo, setDelUserInfo] = useState({})
    const rowSelection = {
        onSelect: (record) => {
            console.log('record', record.userId);
            setDelUserInfo(record)
        },
    };
    function delUser(delUserInfo) {
        console.log(delUserInfo);
        userApi.delUser(delUserInfo.userId).then(res => {
            if (res.status == 200) {
                message.success('删除成功')
                search()
            }
        })
    }

    //初始渲染页面
    const param = { pageSize: pageSize, username: '', deptId: '' }
    useEffect(() => {
        search()
    }, [])
    function search() {
        userApi.getAllUser(param).then(res => {
            console.log(res);
            setListUser([...res.data.rows])
            setTotalUser(res.data.total)
        })
    }

    //表格渲染性别功能
    function getSex(props) {
        if (props == 0) {
            return <span>男</span>
        } else if (props == 1) {
            return <span>女</span>
        } else {
            return <span>保密</span>
        }
    }
    //表格渲染状态功能
    function getStatus(props) {
        if (props == 1) {
            return <span className='green'>有效</span>
        } else {
            return <span className='red'>锁定</span>
        }
    }

    //表头搜索栏功能
    const handleChange = (value) => {
        console.log(value);
    };
    const onFinish = (values) => {
        console.log('Success:', values);
        const param = { pageSize: '10', username: '', deptId: '' }
        if (values.username) param.username = values.username
        if (values.deptId) param.deptId = values.deptId
        if (values.createTime) {
            const createTimeFrom = moment(values.createTime[0]._d).format("YYYY-MM-DD")
            const createTimeTo = moment(values.createTime[1]._d).format("YYYY-MM-DD")
            param.createTimeFrom = createTimeFrom
            param.createTimeTo = createTimeTo
        }
        userApi.getAllUser(param).then(res => {
            setListUser([...res.data.rows])
            setTotalUser(res.data.total)
        })
    };
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    const { RangePicker } = DatePicker;

    //添加用户

    const onFinishUser = (values) => {
        console.log(values);
        userApi.addUser(values).then(res => {
            if (res.status == 200) {
                message.success('添加成功,初始密码为1234qwer')
                search()
            }
        })
    };
    const onFinishFailedUser = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    //添加及修改用户时状态及性别单选功能
    const [statusvalue, setStatusValue] = useState(1);
    const [sexvalue, setSexValue] = useState(1);
    const onChangeStatus = (e) => {
        console.log('radio checked', e.target.value);
        setStatusValue(e.target.value);
    };
    const onChangeSsex = (e) => {
        console.log('radio checked', e.target.value);
        setSexValue(e.target.value);
    };

    //修改用户

    const onFinishEdit = (values) => {
        userApi.editUser({ ...values, userId: editUser.userId }).then(res => {
            console.log(res);
            if (res.status == 200) {
                message.success('修改成功')
                search()
            }
        })
    };
    const onFinishFailedEdit = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    //重置搜索
    const [form] = Form.useForm();
    function reset() {
        form.resetFields()
        window.location.reload()
    }

    //重置密码及导出excel
    const [isModalOpenReset, setIsModalOpenReset] = useState(false);
    const handleChangeResetOrToExcel = (value) => {
        console.log(value);
        console.log(delUserInfo);
        if (delUserInfo.userId) {
            setIsModalOpenReset(true)
        } else if (value === '导出excel') {
            downloadUserInfoApi()
            message.success('导出成功')
        } else {
            message.error('请先选择要操作的对象')
        }
    }
    const handleOkReset = () => {
        setIsModalOpenReset(false);
        const Resetparam = {
            usernames: delUserInfo.username,

        }
        userApi.resetPassword({
            usernames: delUserInfo.username
        }).then(res => {
            message.success('重置密码成功')
            search()
        })
    };
    const handleCancelReset = () => {
        setIsModalOpenReset(false);
    };
    return (
        <>
            <Breadcrumb>
                <Breadcrumb.Item>系统主页</Breadcrumb.Item>
                <Breadcrumb.Item>
                    系统管理
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                   用户管理
                </Breadcrumb.Item>
            </Breadcrumb>

            {/* 表头搜索栏 */}

            <div style={{marginTop:20}}>
                <Form
                    ref={formRef}
                    form={form}
                    labelCol={{
                        span: 4,
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                >
                    <Row>
                        <Col span={12}>
                            <Form.Item
                                label="用户名"
                                name="username"
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="部门"
                                name="deptId"
                            >
                                <Select onChange={handleChange}>
                                    <Select.Option value='1'>开发部</Select.Option>
                                    <Select.Option value='2'>开发一部</Select.Option>
                                    <Select.Option value='4'>市场部</Select.Option>
                                    <Select.Option value='5'>人事部</Select.Option>
                                    <Select.Option value='6'>测试部</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <Form.Item
                                label='创建时间'
                                name='createTime'
                            >
                                <RangePicker />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                wrapperCol={{
                                    offset: 16,
                                    span: 8,
                                }}
                            >
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button onClick={reset}>重置</Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>

            {/* 删除，新增用户按钮 */}

            <div style={{ marginBottom: 20 }}>
                <Button onClick={showDefaultDrawer} type='primary'>新增</Button>
                <Popconfirm
                    title={`你确定要删除${delUserInfo.username}这条数据吗`}
                    onConfirm={() => delUser(delUserInfo)}
                    okText="是"
                    cancelText="否"
                >
                    <Button type='danger'>删除</Button>
                </Popconfirm>

                <Select
                    defaultValue="更多操作"
                    style={{
                        width: 120,
                    }}
                    onChange={handleChangeResetOrToExcel}
                    options={[
                        { value: '密码重置', label: '密码重置' },
                        { value: '导出excel', label: '导出excel' }
                    ]}
                />
            </div>
            <Table
                columns={columns}
                rowSelection={{
                    ...rowSelection,
                }}
                dataSource={listUser}
                rowKey='password'
                onChange={handleChangeSort}
                pagination={
                    { total: totalUser }
                }
            />

            {/* 新增用户抽屉 */}

            <Drawer
                title='新增用户'
                placement="right"
                onClose={onClose}
                open={open}
                closable={false}
                maskClosable={false}
                footer={
                    <Space>
                        <Button type="primary" onClick={onClose}>
                            点击关闭
                        </Button>
                    </Space>
                }
                footerStyle={{ textAlign: 'right' }}
            >
                <Form
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={onFinishUser}
                    onFinishFailed={onFinishFailedUser}
                    autoComplete="off"
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[
                            {
                                required: true,
                                message: '请输入用户名',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="password"
                        initialValue='1234qwer'
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item
                        label="邮箱"
                        name="email"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="手机"
                        name="mobile"
                        rules={[
                            {
                                required: true,
                                message: '请输入手机号',
                            }
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="角色"
                        name="roleId"
                        rules={[
                            {
                                required: true,
                                message: '请选择角色',
                            },
                        ]}
                    >
                        <Select>
                            <Select.Option value='1'>管理员</Select.Option>
                            <Select.Option value='2'>注册用户</Select.Option>
                            <Select.Option value='72'>普通用户</Select.Option>
                            <Select.Option value='73'>商户</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label='部门'
                        name="deptId"
                        rules={[
                            { required: true, message: '请选择部门' }
                        ]}
                    >
                        <Select>
                            <Select.Option value={1}>开发部</Select.Option>
                            <Select.Option value={2}>开发一部</Select.Option>
                            <Select.Option value={3}>开发二部</Select.Option>
                            <Select.Option value={4}>市场部</Select.Option>
                            <Select.Option value={5}>人事部</Select.Option>
                            <Select.Option value={6}>测试部</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label='状态'
                        name='status'
                        rules={[
                            { required: true, message: '请选择状态' }
                        ]}
                    >
                        <Radio.Group onChange={onChangeStatus} value={statusvalue}>
                            <Radio value='1'>有效</Radio>
                            <Radio value='0'>锁定</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item
                        label='性别'
                        name='ssex'
                        rules={[
                            { required: true, message: '请选择性别' }
                        ]}
                    >
                        <Radio.Group onChange={onChangeSsex} value={sexvalue}>
                            <Radio value='0'>男</Radio>
                            <Radio value='1'>女</Radio>
                            <Radio value='2'>保密</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 8,
                            span: 16,
                        }}
                    >
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>

            {/* //修改用户抽屉 */}

            <Drawer
                title="修改用户"
                width={500}
                onClose={onCloseEdit}
                open={openEdit}
                closable={false}
                maskClosable={false}
                footer={
                    <Space>
                        <Button type="primary" onClick={onCloseEdit}>
                            点击关闭
                        </Button>
                    </Space>
                }
                footerStyle={{ textAlign: 'right' }}
            >
                <Form
                    form={formEdit}
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    onFinish={onFinishEdit}
                    onFinishFailed={onFinishFailedEdit}
                    autoComplete="off"
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[
                            {
                                required: true,
                                message: '请输入用户名',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="邮箱"
                        name="email"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="手机"
                        name="mobile"
                        rules={[
                            {
                                required: true,
                                message: '请输入手机号',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label='角色'
                        name='roleId'
                        rules={[
                            { required: true, message: '请选择角色' }
                        ]}
                    >
                        <Select>
                            <Select.Option value='1'>管理员</Select.Option>
                            <Select.Option value='2'>注册用户</Select.Option>
                            <Select.Option value='3'>普通用户</Select.Option>
                            <Select.Option value='4'>商户</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label='部门'
                        name="deptId"
                    >
                        <Select>
                            <Select.Option value={1}>开发部</Select.Option>
                            <Select.Option value={2}>开发一部</Select.Option>
                            <Select.Option value={3}>开发二部</Select.Option>
                            <Select.Option value={4}>市场部</Select.Option>
                            <Select.Option value={5}>人事部</Select.Option>
                            <Select.Option value={6}>测试部</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label='状态'
                        name='status'
                        rules={[
                            { required: true, message: '请选择状态' }
                        ]}
                    >
                        <Radio.Group onChange={onChangeStatus} value={statusvalue}>
                            <Radio value='1'>有效</Radio>
                            <Radio value='0'>锁定</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item
                        label='性别'
                        name='ssex'
                        rules={[
                            { required: true, message: '请选择性别' }
                        ]}
                    >
                        <Radio.Group onChange={onChangeSsex} value={sexvalue}>
                            <Radio value='0'>男</Radio>
                            <Radio value='2'>女</Radio>
                            <Radio value='null'>保密</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 8,
                            span: 16,
                        }}
                    >
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>

            {/* //用户信息modal框 */}

            <Modal title="用户信息" open={isModalOpen} maskClosable={true} onOk={handleOk} onCancel={handleCancel} footer={null} width={700} height={600}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignContent: 'space-between' }}>
                    <div>
                        <img src={"http://xawn.f3322.net:8002/distremote/static/avatar/" + userInf.avatar} style={{ width: 115, height: 115 }} />
                    </div>
                    <div>
                        <div style={{ marginBottom: 10 }}><img src={Zhanghu} style={{ width: 15, height: 15, marginRight: 10 }} />账户：{userInf.username}</div>
                        <div style={{ marginBottom: 10 }}><img src={Juese} style={{ width: 15, height: 15, marginRight: 10 }} />角色：{userInf.roleName}</div>
                        <div style={{ marginBottom: 10 }}><img src={Xingbie} style={{ width: 15, height: 15, marginRight: 10 }} />性别：{userInf.ssex === '0' ? '男' : '保密'}</div>
                        <div style={{ marginBottom: 10 }}><img src={Dianhua} style={{ width: 15, height: 15, marginRight: 10 }} />电话：{userInf.mobile}</div>
                        <div style={{ marginBottom: 10 }}><img src={Youxiang} style={{ width: 15, height: 15, marginRight: 10 }} />邮箱：{userInf.email}</div>
                    </div>
                    <div>
                        <div style={{ marginBottom: 10 }}><img src={Bumen} style={{ width: 15, height: 15, marginRight: 10 }} />部门：{userInf.deptName}</div>
                        <div style={{ marginBottom: 10 }}><img src={Zhuangtai} style={{ width: 15, height: 15, marginRight: 10 }} />状态：{userInf.status === '1' ? '有效' : '锁定'}</div>
                        <div style={{ marginBottom: 10 }}><img src={Chuangjian} style={{ width: 15, height: 15, marginRight: 10 }} />创建时间：{userInf.createTime}</div>
                        <div style={{ marginBottom: 10 }}><img src={Denglu} style={{ width: 15, height: 15, marginRight: 10 }} />最近登录：{userInf.lastLoginTime}</div>
                        <div style={{ marginBottom: 10 }}><img src={Miaoshu} style={{ width: 15, height: 15, marginRight: 10 }} />描述：{userInf.description}</div>
                    </div>
                </div>
            </Modal>

            {/* 重置密码modal框 */}
            <Modal title="确定重置选中用户的密码吗？" open={isModalOpenReset} onOk={handleOkReset} onCancel={handleCancelReset}>
                当您点击确定按钮后，这些用户的密码将会重置为1234qwer
            </Modal>
        </>
    )
}
